import { createRouter, createWebHashHistory } from "vue-router";
import { setupLayouts } from "virtual:generated-layouts";
import generatedRoutes from 'virtual:generated-pages';
import { useUser } from '@/pinia-store/user.js';
import { useMenu } from '@/pinia-store/index'
import define from "@/utils/define";

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: setupLayouts(generatedRoutes),
});

// 查找当前路由页面
function fnidRouter(fullPath,sysRouterList) {
  sysRouterList.forEach(item => {
    if (fullPath === item.path) {
      useMenu().updataSelectedKeys(item.id)
      document.title = item.meta.title
      return 
    }
    if (item.children) {
      fnidRouter(fullPath, item.children)
    }
  })
}

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || define.title
  if (to.fullPath && to.fullPath!=='/') {
    const sysRouters = localStorage.getItem('menuList') ? JSON.parse(localStorage.getItem('menuList')) : []
    fnidRouter(to.fullPath, sysRouters)
  }
  if (!useUser().token && to.path!=='/login') {
    next('/login')
  } else {
    next()
  }
})

export default router;  
